import React from 'react';
import city from './cityList.module.scss'
import { getCityList, getCityCode } from '../../utils/interface'
import { getUrlParam, isOrigin } from '../../utils/tools'
import Loading from '../../comm/loading'

class CityList extends React.Component {
  constructor(props) {
    super(props);
    console.log(props)
    this.state = {
      index: null,
      list: [],
      cityName: "",
      distanceInfo: {},
      cityId: "",
      loadingState: true
    };
  }
  render () {
    return (
      <div className={city.CityList}>
        <Loading loadingState={this.state.loadingState} />
        <header className={city['city-header']}>
          <div className={city.distance}>
            <p>当前定位:</p>
            <span>{this.state.cityName}</span>
          </div>
          <p className={city.reset} onClick={this.resetLocation.bind(this)}>重新定位</p>
        </header>
        <div className={city.content}>
          <p className={city.title}>开通城市</p>
          <ul>
            {this.state.list.map((item, idx) => {
              return (
                <li key={idx} onClick={this.select.bind(this, idx, item)} className={this.state.index === idx ? city.active : ''}>{item.cityName}</li>
              )
            })}
          </ul>
        </div>
      </div>
    );
  }
  select (n, data) {
    this.setState({
      index: n
    })
    console.log(window.my)
    // document.write(JSON.stringify(window.my.navigateBack))
    if (isOrigin() === "WeiXIN") {
      window.wx.miniProgram.postMessage({ data: { form: 1, lat: data.lat, lot: data.lot, cityId: data.cityId } })
      window.wx.miniProgram.navigateBack()
    } else if (isOrigin === "Alipay") {
      window.my.postMessage({ data: { form: 1, lat: data.lat, lot: data.lot, cityId: data.cityId } })
      window.my.navigateTo({ url: '/pages/index/index' })
    }

  }
  resetLocation () {
    window.wx.miniProgram.postMessage({ data: { form: 1, cityId: this.state.cityId } })
    window.wx.miniProgram.navigateBack()
  }
  componentDidMount () {
    document.title = "城市"
    let that = this
    getCityCode({ lng: Number(getUrlParam('lot')), lat: Number(getUrlParam('lat')) }).then(res => {
      console.log(res.data, '我的地址')
      that.state.distanceInfo.lat = res.data.result.result.location.lat
      that.state.distanceInfo.lot = res.data.result.result.location.lng
      let code = res.data.result.result.addressComponent.city_code;
      let cityid = code.substring(3, code.length);
      that.setState({
        cityName: res.data.result.result.addressComponent.city,
        cityId: cityid
      })
    })
    getCityList().then(res => {
      console.log(res.data.result, '城市列表')
      this.setState({
        list: res.data.result,
        loadingState: false,
      })
    })
  }
}
export default CityList;